package com.coolweather.android;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.coolweather.android.db.City;
import com.coolweather.android.db.County;
import com.coolweather.android.db.Province;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private ListView listView;
    private ArrayAdapter<String> adapter;
    private List<Province> provinceList;
    private ProgressDialog progressDialog;
    private List<City> cityList;
    private List<County> countyList;
    private List<String> dataList = new ArrayList<>();
    private Province selectProvince;
    private Button backButton;
    private TextView titleText,dataTotal;
    public static final int LEVEL_PROVINCE = 0;
    public static final int LEVEL_CITY = 1;
    public static final int LEVEL_COUNTY = 2;
    private int currentLevel;
    private City selectCity;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SharedPreferences sp= PreferenceManager.getDefaultSharedPreferences(this);

        backButton = (Button) findViewById(R.id.back_button);
        titleText = (TextView)findViewById(R.id.title_text);
        dataTotal = (TextView)findViewById(R.id.data_total);
        listView = (ListView) findViewById(R.id.list);
        adapter = new ArrayAdapter<>(MainActivity.this,
                android.R.layout.simple_list_item_1, dataList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (currentLevel == LEVEL_PROVINCE) {
                    selectProvince = provinceList.get(i);
                    int provinceCode = selectProvince.getProvinceCode();
                    displayCity();
                }else if(currentLevel == LEVEL_CITY){
                    selectCity = cityList.get(i);
                    int cityCode = selectCity.getCityCode();
                    displayCounty();
                }else if(currentLevel == LEVEL_COUNTY){
                    String weatherId = countyList.get(i).getWeatherId();
                    Intent intent = new Intent(MainActivity.this,WeatherActivity.class);
                    intent.putExtra("weather_id",weatherId);
                    startActivity(intent);
                    MainActivity.this.finish();
                }
            }
        });
        createBase();
        displayProvince();
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(currentLevel == LEVEL_COUNTY){
                    displayCity();
                }else if(currentLevel == LEVEL_CITY){
                    displayProvince();
                }
            }
        });
    }
    /*创建数据库*/
    private void createBase() {
        Connector.getDatabase();
    }
    /* 获取数据*/
    private void getDataThread(String address, String type) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url(address).build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    if ("province".equals(type)) {
                        parseProvinceData(responseData);
                    }else if ("city".equals(type)) {
                        parseCityData(responseData);
                    }else if ("county".equals(type)) {
                        parseCountyData(responseData);
                    }

                    Log.d("info", responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    /*解析省份数据*/
    private void parseProvinceData(String data) throws JSONException {
        JSONArray allProvinces = new JSONArray(data);
        for (int i = 0; i < allProvinces.length(); i++) {
            JSONObject provinceObject = allProvinces.getJSONObject(i);
            String provinceName = provinceObject.getString("name");
            int provinceCode = provinceObject.getInt("id");
            Log.d("info", provinceName);
            Province db = new Province();
            db.setProvinceName(provinceName);
            db.setProvinceCode(provinceCode);
            db.setId(1);
            db.save();
        }
    }
    /*解析市级数据*/
    private void parseCityData(String data) throws JSONException {
        JSONArray allCities = new JSONArray(data);
        int provinceCode = selectProvince.getProvinceCode();
        for (int i = 0; i < allCities.length(); i++) {
            JSONObject cityObject = allCities.getJSONObject(i);
            String cityName = cityObject.getString("name");
            int cityCode = cityObject.getInt("id");
            Log.d("info", cityName);
            City db = new City();
            db.setCityName(cityName);
            db.setProvinceId(provinceCode);
            db.setCityCode(cityCode);
            db.setId(cityCode);
            db.save();
        }
    }
    /*解析乡级数据*/
    private void parseCountyData(String data) throws JSONException {
        JSONArray allCounty = new JSONArray(data);
        int cityCode = selectCity.getCityCode();
        for (int i = 0; i < allCounty.length(); i++) {
            JSONObject countyObject = allCounty.getJSONObject(i);
            String countyName = countyObject.getString("name");
            int countyCode = countyObject.getInt("id");
            String weather_id = countyObject.getString("weather_id");
            Log.d("info", countyName);
            County db = new County();
            db.setCountyName(countyName);
            db.setWeatherId(weather_id);
            db.setCityId(cityCode);
            db.save();
        }
    }
    /* 显示省份数据*/
    private void displayProvince(){
        titleText.setText("中国天气");
        backButton.setVisibility(View.GONE);
        provinceList = DataSupport.findAll(Province.class);
        if (provinceList.size() > 0) {
            dataList.clear();
            for (Province province : provinceList) {
                dataList.add(province.getProvinceName());
            }
            adapter.notifyDataSetChanged();
            currentLevel = LEVEL_PROVINCE;
            dataTotal.setText("省数据共计:"+provinceList.size()+"条");
        } else {
            String url = "http://guolin.tech/api/china";
            getDataThread(url, "province");
        }
    }
    /*显示市级数据 */
    private void displayCity(){
        titleText.setText(selectProvince.getProvinceName());
        backButton.setVisibility(View.VISIBLE);
        int provinceCode = selectProvince.getProvinceCode();
        cityList = DataSupport.where("provinceid = ?",String.valueOf(provinceCode)).find(City.class);
        if (cityList.size() > 0) {
            dataList.clear();
            for (City city: cityList) {
                dataList.add(city.getCityName());
            }
            adapter.notifyDataSetChanged();
            currentLevel = LEVEL_CITY;
            dataTotal.setText("市数据共计:"+cityList.size()+"条");
        } else {
            String url = "http://guolin.tech/api/china/" + provinceCode;
            getDataThread(url, "city");
        }
    }

    private void displayCounty(){
        titleText.setText(selectCity.getCityName());
        backButton.setVisibility(View.VISIBLE);
        int cityCode = selectCity.getCityCode();
        countyList = DataSupport.where("cityid = ?",String.valueOf(cityCode)).find(County.class);
        if (countyList.size() > 0) {
            dataList.clear();
            for (County county: countyList ) {
                dataList.add(county.getCountyName());
            }
            adapter.notifyDataSetChanged();
            currentLevel = LEVEL_COUNTY;
            dataTotal.setText("乡数据共计:"+countyList.size()+"条");
        } else {
            int provinceCode = selectProvince.getProvinceCode();
            String url = "http://guolin.tech/api/china/" + provinceCode+"/"+cityCode;
            getDataThread(url, "county");
        }
    }
}
